/**
 * 描述: 连接mysql模块
 * 作者: kq
 * 日期: 2022-11-15
 */

const mysql = require("mysql");
const config = require("../db/dbConfig");

// 连接mysql
function connect() {
  const { host, user, password, database } = config;
  return mysql.createConnection({
    host,
    user,
    password,
    database,
  });
}

// 新建查询连接
function querySql(sql, data) {
  const conn = connect();
  return new Promise((resolve, reject) => {
    try {
      conn.query(sql, data, (err, res) => {
        if (err) {
          console.log("失败=", err);
          reject(err);
        } else {
          console.log("成功=", res);
          resolve(res);
        }
      });
    } catch (e) {
      reject(e);
    } finally {
      // 释放连接
      conn.end();
    }
  });
}

// 插入数据
function insertOne(sql, data) {
  return new Promise((resolve, reject) => {
    querySql(sql, data)
      .then((res) => {
        console.log("res===", res);
        if (res && res.affectedRows) {
          resolve(res);
        } else {
          resolve(null);
        }
      })
      .catch((err) => {
        reject(err);
      });
  });
}
// 查询一条语句
function queryOne(sql) {
  return new Promise((resolve, reject) => {
    querySql(sql)
      .then((res) => {
        console.log("res===", res);
        if (res && res.length > 0) {
          resolve(res[0]);
        } else {
          resolve(null);
        }
      })
      .catch((err) => {
        reject(err);
      });
  });
}

// 处理入参
function handlePayload(obj = {}) {
  const keys = Object.keys(obj);
  keys.forEach((key) => {
    if (!obj[key]) {
      obj[key] = null;
    }
  });
  return obj;
}
module.exports = {
  querySql,
  queryOne,
  insertOne,
  handlePayload,
};
